package cs4280.ass2.admin.action;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;

import cs4280.ass2.entity.Officer;
import cs4280.ass2.entity.User;
import cs4280.ass2.exception.ValidateException;
import cs4280.ass2.persistence.OfficerDao;
import cs4280.ass2.util.UserUtils;

public class OfficerEditAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String START_DATE_FORMAT = "dd/MM/yyyy";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		if (StringUtils.isBlank(id)) {
			resp.sendRedirect("list.do");
		} else {
			Officer officer = OfficerDao.getInstance().retrieveOfficer(Long.valueOf(id));
			req.setAttribute("officer", officer);
			getServletContext().getRequestDispatcher("/admin/officer/edit.jsp").forward(req, resp);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = StringUtils.trim(req.getParameter("id"));
		String login = StringUtils.trim(req.getParameter("login"));
		String firstName = StringUtils.trim(req.getParameter("firstName"));
		String lastName = StringUtils.trim(req.getParameter("lastName"));
		String appUserStatus = StringUtils.trim(req.getParameter("appUserStatus"));

		Officer officer = OfficerDao.getInstance().retrieveOfficer(NumberUtils.toLong(id, 0));

		if (officer != null) {
			
			officer.setLogin(login);
			officer.setFirstName(firstName);
			officer.setLastName(lastName);
			officer.setAppUserStatus(appUserStatus);
			officer.setModifyDate(new Date());
			officer.setModifyUser(0);
			officer.setType(User.USER_TYPE_OFFCIER);
			
			try {
				UserUtils.validate(officer);
				OfficerDao.getInstance().updateOfficer(officer);
				req.setAttribute("message.info", "message.info.officer.updatesuccess");
				getServletContext().getRequestDispatcher("/admin/officer/list.do").forward(req, resp);
			} catch (ValidateException e) {
				req.setAttribute("message.error", e.getMessage());
				// set it back to request so that changes can be preserve in the
				// form.
				req.setAttribute("officer", officer);
				getServletContext().getRequestDispatcher("/admin/officer/edit.jsp").forward(req, resp);
			}
		} else {
			// input id not found, just redirect to list.do
			resp.sendRedirect("list.do");
		}
	}
}
